package com.cardbaobao.cardbabyclient.ui.activity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.AgreementWebViewActivity;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.LoansUtils;
import com.cardbaobao.cardbabyclient.utils.RegularUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.utils.ViewUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.gyf.barlibrary.ImmersionBar;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Administrator on 2017/1/4.
 * 找回密码
 */
public class GetBackPasswordActivity extends BaseActivity{
    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.edtext_phone)
    EditText mPhoneEd;//手机号输入框
    @BindView(R.id.msg_code)
    EditText mMsgCodeEd;//验证码输入框
    @BindView(R.id.edtext_pass)
    EditText mPassEd;//密码输入框
    @BindView(R.id.agreement_checkbox)
    CheckBox agreementCb;//协议

    @BindView(R.id.send_msg_code)
    TextView mSendMsgCode;//发送验证码

    private String msgCode = "";
    private String mPhone = "";

    private MyCountDownTimer timer;

    @Override
    protected void initView(Bundle savedInstanceState) {
        ImmersionBar.with(this).statusBarDarkFont(true,Constant.STATUS_BAR_FONT_ALPHA).keyboardEnable(true).init();
        initIntent();
        titleBar.setRightViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mCurrentPageId= Self.Page.app_reset_pwd_page;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_get_back_password;
    }

    @Override
    protected void onResume() {
        super.onResume();
        UmengEventUtils.pageEvent(mContext,
                ApplicationHelper.getApplicationContext().getString(R.string.event_0x032));
        GoogleAnalyticsUtil.setScreenName(Google.GET_BACK_PWD);
    }

    @OnClick({R.id.send_msg_code,R.id.tv_agreement,R.id.commit_data})
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.send_msg_code:
                //发送验证码
                checkPhone();
                break;
            case R.id.tv_agreement:
                mIntent.setClass(mContext, AgreementWebViewActivity.class);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TITLE_S,"卡宝宝申请条款");
                mIntent.putExtra(AgreementWebViewActivity.WEB_URL_S,URLUtil.REGISTRATION_AGREEMENT);
                startActivity(mIntent);
                break;
            case R.id.commit_data:
                //确认修改
                if(agreementCb.isChecked()){
                    getBackPassword();
                }else{
                    ToastUtil.showToast("同意《卡宝宝申请条款》后才能进行下一步操作");
                }
                break;
        }
    }

    @OnCheckedChanged(value = R.id.checkbox)
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
        ViewUtil.toggleEditTextInputType(mPassEd,isChecked);
        try{
            mPassEd.setSelection(mPassEd.getText().toString().trim().length());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //修改密码
    private void getBackPassword(){
        String phone = mPhoneEd.getText().toString().trim();
        String msg = "";
        if(!TextUtils.isEmpty(phone) && RegularUtil.isPhoneNumber(phone)){
            String msgCodes = mMsgCodeEd.getText().toString().trim();
            if(!phone.isEmpty() && msgCode.equals(msgCodes)){
                if(phone.equals(mPhone)){
                    String password = mPassEd.getText().toString().trim();
                    if(!TextUtils.isEmpty(password) && password.length() >= 6){
                        getBackPassDate(phone,password);
                        GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_ORD, Google.ACTION_FORGET_PWD_SUM);
                    }else{
                        msg = "密码最少为6位";
                    }
                }else{
                    msg="非法操作";
                }
            }else{
                msg = "请输入正确的验证码";
            }
        }else{
            msg = "请输入正确的手机号";
        }
        if(!TextUtils.isEmpty(msg)){
            ToastUtil.showToast(msg);
        }
    }

    /**
     * 重置密码
     * @param phone
     * @param newPass
     */
    private void getBackPassDate(String phone,String newPass){
        Observable<String> observable= Api.resetPwd(phone,newPass);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject object= JSON.parseObject(s);
                ToastUtil.showToast(object.getString("msg"));
                if (object.getIntValue("code")==1) {
                    finish();
                }
            }
        });
    }

    //检测手机号是否注册过
    private void checkPhone(){
        final String phone = mPhoneEd.getText().toString().trim();
        if(RegularUtil.isPhoneNumber(phone)){
            showProgressDialog(false);
            Observable<String> observable=Api.checkPhoneRegistered(phone);
            observable.subscribe(new Subscriber<String>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    dismissProgressDialog();
                    ToastUtil.showToast(ApplicationHelper.
                            getApplicationContext().
                            getString(R.string.string_request_server_fail));
                }

                @Override
                public void onNext(String s) {
                    JSONObject object=JSON.parseObject(s);
                    if(object.getIntValue("code")==1){
                        sendMsgCode(phone);//执行发送短信
                        GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_ORD, Google.ACTION_FORGET_PWD_CODE);
                    }else{
                        dismissProgressDialog();
                        ToastUtil.showToast("该手机号还未注册");
                    }
                }
            });
        }else{
            ToastUtil.showToast("请输入正确的手机号码");
        }
    }

    //发送验证码
    private void sendMsgCode(final String phone){
        msgCode = String.valueOf(LoansUtils.getMsgCode());
        Observable<String> observable=
                Api.sendSms(phone,Constant.VERIFY_CODE_TYPE,msgCode,Constant.GDX030105);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
                dismissProgressDialog();
                msgCode = "";
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject object = JSON.parseObject(s);
                if (object.getIntValue("status") == 1) {
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                    timer = new MyCountDownTimer(90l * 1000l, 1000L);
                    timer.start();
                    mSendMsgCode.setEnabled(false);
                    mSendMsgCode.setText("90s后重发");
                    mSendMsgCode.setTextColor(0xff999999);
                    mPhone = phone;
                } else {
                    msgCode = "";
                }
                ToastUtil.showToast(object.getString("result"));
            }
        });
    }

    //定时器
    private class MyCountDownTimer extends CountDownTimer {
        private MyCountDownTimer(long millisInFuture, long countDownInterval){
            super( millisInFuture,countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mSendMsgCode.setText(millisUntilFinished/1000+"s后重发");
        }

        @Override
        public void onFinish() {
            mSendMsgCode.setText("发送验证码");
            mSendMsgCode.setTextColor(0xffffab18);
            mSendMsgCode.setEnabled(true);
            timer = null;
        }
    }
}
